

import onload from '../util/onload';
import tracker from '../util/tracker';
// import formatTime from '../util/formatTime';


export function timing() {
    let FMP, LCP;
    // 增加一个性能条目的观察者  --- 观察页面中主要元素
    new PerformanceObserver((entryList,observer)=>{
        let perfEntries = entryList.getEntries();
        FMP = perfEntries[0];
        observer.disconnect();
    }).observe({ entryTypes: ['element'] });
    // 增加一个性能条目的观察者  --- 观察页面中最大的元素
    new PerformanceObserver((entryList,observer)=>{
        let perfEntries = entryList.getEntries();
        const lastEntry = perfEntries[perfEntries.length - 1];
        LCP = lastEntry;
        observer.disconnect();
    }).observe({ entryTypes: ['largest-contentful-paint'] });

 
    onload(function () {
        setTimeout(()=>{
            const {
                fetchStart, //请求开始
                connectStart, //开始连接
                connectEnd, //结束连接
                requestStart, //开始请求
                responseStart,//响应开始
                responseEnd,//响应结束
                domLoading,//开始解析dom
                domInteractive,//dom结构结束解析
                domContentLoadedEventStart,//domContentLoaded事件发生的时间
                domContentLoadedEventEnd,//domContentLoaded事件脚本执行完毕的时间,domReady的时间
                loadEventStart//oad回调函数开始执行的时间
            } = performance.timing
            tracker.send({
                kind: 'experience', //用户体验指标
                type: 'timing',
                connectTime: connectEnd - connectStart,//TCP连接耗时
                ttfbTime: responseStart - requestStart,//ttfb
                responseTime: responseEnd - responseStart,//Response响应耗时
                parseDOMTime: loadEventStart - domLoading,//DOM解析渲染耗时
                domContentLoadedTime: domContentLoadedEventEnd - domContentLoadedEventStart,//DOMContentLoaded事件回调耗时
                timeToInteractive: domInteractive - fetchStart,//首次可交互时间
                loadTime: loadEventStart - fetchStart//完整的加载时间
            });
            const FP = performance.getEntriesByName('first-paint')[0];
            const FCP = performance.getEntriesByName('first-contentful-paint')[0];
            console.log('FP',FP);
            console.log('FCP',FCP);
            console.log('FMP',FMP);
            console.log('LCP',LCP);
            tracker.send({
                kind: 'experience',
                type: 'paint',
                firstPaint: FP ? formatTime(FP.startTime) : 0,
                firstContentPaint: FCP ? formatTime(FCP.startTime) : 0,
                firstMeaningfulPaint: FMP ? formatTime(FMP.startTime) : 0,
                largestContentfulPaint: LCP ? formatTime(LCP.renderTime || LCP.loadTime) : 0
            });
        },3000)
        
    });



}